package com.czn.controller.doctor;

import com.czn.entity.*;
import com.czn.service.*;
import com.czn.utils.PDFUtils;
import com.czn.vo.QueryVo;
import com.czn.vo.ResponseResult;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileSystemView;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ChenZeNan
 * @create 2021-04-26 0:01
 */
@Controller
@RequestMapping("/doctor")
public class DoctorController {
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IAppointmentService appointmentService;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private IOptionService optionService;
    @Autowired
    private IDrugsService drugsService;
    @Autowired
    private ISeekService seekService;
    @Autowired
    private IHospitalizationService hospitalizationService;
    @Autowired
    private IMedicalHistoryService medicalHistoryService;


    /**
     * 医生首页
     *
     * @param queryVo
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(QueryVo queryVo, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        queryVo.setUserId(user.getId());
        Doctor doctor = doctorService.findDoctorByUserId(user.getId());
        PageQuery<Appointment> page = appointmentService.findAppointmentListByDoctor(queryVo);
        model.addAttribute("page", page);
        model.addAttribute("doctor", doctor);
        model.addAttribute("pageNo", queryVo.getPageNo());
        model.addAttribute("patientName", queryVo.getPatientName());
        model.addAttribute("time", queryVo.getTime());
        model.addAttribute("path", "/doctor/index");
        StringBuilder sb = new StringBuilder();
        if (queryVo.getPatientName() != null) {
            sb.append("&patientName=" + queryVo.getPatientName());
        }
        if (queryVo.getTime() != null) {
            sb.append("&time=" + queryVo.getTime());
        }
        model.addAttribute("params", sb.toString());
        return "doctor/index";
    }

    /**
     * 就医
     *
     * @param patientId
     * @param model
     * @return
     */
    @RequestMapping("/seek/{id}/{appointmentId}")
    public String seek(@PathVariable("id") Integer patientId,
                       @PathVariable("appointmentId") Integer appointmentId,
                       Model model) {
        model.addAttribute("patient", patientService.findPatientById(patientId));
        model.addAttribute("options", optionService.findAll());
        model.addAttribute("drugs", drugsService.findAll());
        model.addAttribute("appointmentId", appointmentId);
        return "doctor/seek";
    }

    /**
     * 就诊
     *
     * @param map
     * @return
     */
    @RequestMapping("/seekInfo")
    @ResponseBody
    public ResponseResult seekInfo(@RequestBody Map map, HttpSession session) {
        session.setAttribute("seekInfoMap", map);
        return seekService.save(map, session);
    }

    /**
     * 开药
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/drug", method = RequestMethod.PUT)
    @ResponseBody
    public ResponseResult drug(@RequestBody Map map, HttpSession session) {
        return seekService.update(map, session);
    }

    /**
     * 入院
     *
     * @param hospitalization
     * @return
     */
    @RequestMapping("/zation")
    @ResponseBody
    public ResponseResult zation(@RequestBody Hospitalization hospitalization, HttpSession session, Model model) {
        session.setAttribute("zationMap", hospitalization);
        return hospitalizationService.addHospitalization(hospitalization);
    }

    /**
     * 查看病史
     *
     * @param patientId
     * @param queryVo
     * @param model
     * @return
     */
    @RequestMapping("/medicalHistory/{id}")
    public String medicalHistory(@PathVariable("id") Integer patientId, QueryVo queryVo, Model model) {
        queryVo.setPatientId(patientId);
        PageQuery<Medicalhistory> page = medicalHistoryService.findMedicalHistoryList(queryVo);
        model.addAttribute("page", page);
        model.addAttribute("pageNo", queryVo.getPageNo());
        model.addAttribute("path", "/doctor/medicalHistory/" + patientId);
        model.addAttribute("params", "");
        return "doctor/medicalHistory";
    }

    /**
     * 打印就诊单
     *
     * @param patientId
     * @param appointmentId
     * @param session
     * @return
     */
    @RequestMapping(value = "/printSeek/{id}/{appointmentId}", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult printSeek(@PathVariable("id") Integer patientId,
                                    @PathVariable("appointmentId") Integer appointmentId,
                                    HttpSession session) {
        User user = (User) session.getAttribute("user");
        Doctor doctor = doctorService.findDoctorByUserId(user.getId());
        Seek seek = seekService.findSeekById(patientId, appointmentId, session);
        seek.setPatientName(patientService.findPatientById(patientId).getName());
        seek.setDoctorName(doctor.getName());
        //createSeekInfo，第三个参数填空字符串就是生成在项目根目录里面，要是想生成在别的路径，例：D:\\ 就是生成在D盘根目录
        String path = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
        String message = PDFUtils.createSeekInfo(seek, optionService, path+"\\");
        return new ResponseResult("600", message);
    }

    /**
     * 就诊完成
     *
     * @param id
     * @return
     */
    @RequestMapping("/finishSeek/{id}")
    @ResponseBody
    public ResponseResult finishSeek(@PathVariable("id") Integer id, HttpSession session) {
        // 更改status状态
        Appointment appointment = new Appointment();
        appointment.setStatus("3");
        appointment.setId(id);
        ResponseResult result = appointmentService.editAppointment(appointment);
        Map seekInfoMap = (Map) session.getAttribute("seekInfoMap");
        Hospitalization hospitalization = (Hospitalization) session.getAttribute("zationMap");
        if (seekInfoMap != null && hospitalization != null) {
            Medicalhistory medicalhistory = new Medicalhistory();
            medicalhistory.setPatientId(Integer.valueOf(String.valueOf(seekInfoMap.get("patientId"))));
            medicalhistory.setName(String.valueOf(seekInfoMap.get("illnessName")));
            medicalhistory.setTime(new Date());
            User user = (User) session.getAttribute("user");
            Doctor doctor = doctorService.findDoctorByUserId(user.getId());
            medicalhistory.setDoctorId(doctor.getId());
            medicalhistory.setHospitalizationId(hospitalization.getId());
            medicalHistoryService.addMedicalHistory(medicalhistory);
        }
        return result;
    }


    /**
     * 根据科室查询医生
     *
     * @param department
     * @return
     */
    @RequestMapping("/getList/{department}")
    @ResponseBody
    public List<Doctor> getList(@PathVariable String department) {
        List<Doctor> doctors = doctorService.findDoctorListByDepartment(department);
        return doctors;
    }
}
